package com.study.controller;

import com.study.common.Result;
import com.study.common.ResultCode;
import com.study.entity.company.Company;
import com.study.entity.company.Department;
import com.study.service.CompanyService;
import com.study.service.DepartmentService;
import com.study.vo.company.DeptListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author wfw
 * @Date 2020/07/12 16:05
 */
@CrossOrigin
@RestController
@RequestMapping(value = "company/department")
public class DepartmentController extends BaseController {
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private CompanyService companyService;

    @PostMapping("")
    public Result save(@RequestBody Department department) {
        /**
         * 设置保存的企业id
         * 使用shiro获取session中保存的ProfileResult中的companyId
         */
        department.setCompanyId(companyId);
        departmentService.save(department);
        return new Result(ResultCode.SUCCESS);
    }

    @GetMapping("")
    public Result findAll() {
        // 指定企业id
        Company company = companyService.findById(companyId);
        List<Department> departments = departmentService.findAll(companyId);
        DeptListResult deptListResult = new DeptListResult(company, departments);
        return new Result(ResultCode.SUCCESS, deptListResult);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable(value = "id") String id) {
        Department department = departmentService.findById(id);
        return new Result(ResultCode.SUCCESS, department);
    }

    @PutMapping("{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody Department department) {
        //1.设置修改的部门id
        department.setId(id);
        departmentService.update(department);
        return new Result(ResultCode.SUCCESS);
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable(value = "id") String id) {
        departmentService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据部门编码和公司id查询部门
     */
    @GetMapping("search")
    public Department findByCode(@RequestParam("code") String code, @RequestParam("companyId") String companyId) {
        return departmentService.findByCode(code, companyId);
    }
}
